package org.extreme.core.plugin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.extreme.core.cfg.IConfig;
import org.extreme.core.exception.PluginsException;

public class Plugins {
	
	public static final Plugins me = new Plugins();
	
	private IConfig cfg;
	
	private List<IPlugin> plugins;
	
	public Plugins(){
		plugins = new ArrayList<IPlugin>();
	}
	
	public Plugins add(IPlugin p){
		plugins.add(p);
		return this;
	}
	
	public Plugins remove(IPlugin p){
		plugins.remove(p);
		return this;
	}
	

	
	@SuppressWarnings("rawtypes")
	public void init(ServletConfig config){
		String configClass = config.getInitParameter("configClass");
		try {
			Class claz = Class.forName(configClass);
			this.cfg = (IConfig) claz.newInstance();
			cfg.ConfigPlugins(Plugins.me);
		} catch (Exception e) {
			e.printStackTrace();
			throw new PluginsException("instance configClass failed");
			
		}
		for(IPlugin p : plugins){
			p.init(config);
		}
	};
	
	public void before(HttpServletRequest req, HttpServletResponse resp){
		for(IPlugin p : plugins){
			p.before(req, resp);
		}
	};
	
	public void service(HttpServletRequest req, HttpServletResponse resp){
		for(IPlugin p : plugins){
			p.service(req, resp);;
		}
	};
	
	public void after(HttpServletRequest req, HttpServletResponse resp){
		for(IPlugin p : plugins){
			p.after(req, resp);
		}
	};
	
	public void destroy(){
		for(IPlugin p : plugins){
			p.destroy();
		}
	};
}
